'use client';

import { useContext, useEffect, useRef, useState } from 'react';
import { OauthClientAdminContext } from '@/contexts/admin/oauth/client';
import UpdateOauthClientInterfaceState from '@/app/[locale]/admin/oauth/client/interface/update/state';

export default function UpdateOauthClientInterfaceAdminPage(this: any) {
  const context = useContext(OauthClientAdminContext);
  const updateModalRef = useRef<HTMLDivElement>(null);
  const [type, setType] = useState({
    state: true,
  });

  useEffect(() => {
    onClickOpenModal();
  }, []);

  function onClickMenu(item: 'state') {
    const newType = {
      state: false,
    };

    newType[item] = true;
    setType(newType);
  }

  function onClickOpenModal() {
    getUpdateModal().show();
  }

  function onClickCloseModal() {
    if (typeof context.setUpdateItem === 'function') {
      context.setUpdateItem(undefined);
    }
    getUpdateModal().hide();
  }

  function getUpdateModal() {
    const current = updateModalRef.current;
    if (!current) {
      throw '更新元素不存在';
    }

    return window.bootstrap.Modal.getOrCreateInstance(current);
  }

  return (
    <div ref={updateModalRef} className="modal fade" data-bs-backdrop="static">
      <div className="modal-dialog modal-xl modal-dialog-scrollable">
        <div className="modal-content">
          <div className="modal-header">
            <h5 className="modal-title">
              {context.oauthClientApiUpdateItem
                ? `${context.oauthClientApiUpdateItem.name} (${context.oauthClientApiUpdateItem.id})`
                : '更新客户端 Api'}
            </h5>
            <button
              onClick={onClickCloseModal}
              type="button"
              className="btn-close"
              aria-label="Close"
            ></button>
          </div>
          <div className="modal-body">
            <div className="row">
              <div className="col-auto">
                <div className="list-group list-group-flush">
                  <button
                    onClick={onClickMenu.bind(this, 'state')}
                    type="button"
                    className="list-group-item list-group-item-action"
                  >
                    状态
                  </button>
                </div>
              </div>
              <div className="col">
                {type.state && (
                  <UpdateOauthClientInterfaceState
                    details={context.oauthClientApiUpdateItem!}
                  />
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
